package org.lql.algo.codecrush.week009.question.type.II;

import org.lql.algo.common.Pair;
import org.lql.algo.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author: liangqinglong
 * @date: 2025-08-20 16:54
 * @description: 102. 二叉树的层序遍历 <a href="https://leetcode.cn/problems/binary-tree-level-order-traversal/description/">...</a>
 **/
public class LevelOrder {

	public List<List<Integer>> levelOrder(TreeNode root) {
		List<List<Integer>> ans = new ArrayList<>();
		if (root == null) {
			return ans;
		}
		Queue<Pair<Integer, TreeNode>> queue = new LinkedList<>();
		queue.offer(new Pair<>(0, root));
		int trackLevel = 0;
		while (!queue.isEmpty()) {
			Pair<Integer, TreeNode> pair = queue.poll();
			int level = pair.getKey();
			TreeNode node = pair.getValue();
			if (level >= trackLevel) {
				ans.add(new ArrayList<>());
				trackLevel++;
			}
			ans.get(level).add(node.val);
			if (node.left != null) {
				queue.offer(new Pair<>(level + 1, node.left));
			}
			if (node.right != null) {
				queue.offer(new Pair<>(level + 1, node.right));
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		LevelOrder levelOrder = new LevelOrder();
		TreeNode root = new TreeNode(3);
		root.left = new TreeNode(9);
		root.right = new TreeNode(20);
		root.right.left = new TreeNode(15);
		root.right.right = new TreeNode(7);
		System.out.println(levelOrder.levelOrder(root));
	}
}
